/**
 * 
 */
package org.tinygroup.remoteconfig.utils;

import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.tinygroup.config.util.ConfigurationUtil;
import org.tinygroup.logger.LogLevel;
import org.tinygroup.logger.Logger;
import org.tinygroup.logger.LoggerFactory;
import org.tinygroup.parser.filter.PathFilter;
import org.tinygroup.remoteconfig.RemoteConfigReadClient;
import org.tinygroup.remoteconfig.config.ConfigValue;
import org.tinygroup.xmlparser.node.XmlNode;
import org.tinygroup.xmlparser.parser.XmlStringParser;

/**
 * @author yanwj
 *
 */
public class RemoteConfigHandler{
	RemoteConfigReadClient remoteConfigReadClient;
	
	private static final Logger LOGGER = LoggerFactory.getLogger(RemoteConfigHandler.class);

	public static final String REMOTE_CONFIG_PATH = "/application/application-properties/remoteconfig";
	
	public static final String REMOTE_CONFIG_PATH_ATTRIBUTE = "enable";
	
	String applicationXML;
	
	public RemoteConfigHandler(String applicationXML ,RemoteConfigReadClient remoteConfigReadClient) {
		this.applicationXML = applicationXML;
		this.remoteConfigReadClient = remoteConfigReadClient;
	}
	
	public void start() {
		if (StringUtils.isNotBlank(applicationXML)) {
			XmlNode xmlNode = loadRemoteConfig(applicationXML);
			if(xmlNode==null){
				return;
			}
			String enable = xmlNode.getAttribute(REMOTE_CONFIG_PATH_ATTRIBUTE);
			if (!StringUtils.equalsIgnoreCase(enable, "true")) {
				return;
			}
		}
		LOGGER.logMessage(LogLevel.INFO, "开始启动远程配置处理器");
		remoteConfigReadClient.start();
		LOGGER.logMessage(LogLevel.INFO, "远程配置处理器启动完成");
		LOGGER.logMessage(LogLevel.INFO, "开始载入远程配置信息");
		Map<String ,ConfigValue> valueMap = remoteConfigReadClient.getAll();
		for (String key : valueMap.keySet()) {
			if (valueMap.get(key) == null || valueMap.get(key).getValue() == null) {
				continue;
			}
			ConfigurationUtil.getConfigurationManager().getConfiguration().put(key ,valueMap.get(key).getValue());
		}
		LOGGER.logMessage(LogLevel.INFO, "载入远程配置信息完成");
	}

	private XmlNode loadRemoteConfig(String applicationConfig) {
		XmlStringParser parser = new XmlStringParser();
		XmlNode root = parser.parse(applicationConfig).getRoot();
		PathFilter<XmlNode> filter = new PathFilter<XmlNode>(root);
		XmlNode appConfig = filter
				.findNode(RemoteConfigHandler.REMOTE_CONFIG_PATH);
		return appConfig; 
	}
	
}
